//! RESTful API实现

use std::sync::Arc;
use tracing::info;

use nacos_core::traits::{NamingService, ConfigService};
use nacos_core::{ServiceInstance, ClusterNode, Result, NacosError};

/// 配置信息结构体
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConfigInfo {
    pub namespace: String,
    pub group: String,
    pub data_id: String,
    pub content: String,
    pub md5: Option<String>,
    pub last_modified: Option<i64>,
}

use super::{ApiResponse, ApiConfig};

/// 命名服务API处理器
pub struct NamingApiHandler {
    naming_service: Arc<dyn NamingService>,
}

impl NamingApiHandler {
    pub fn new(naming_service: Arc<dyn NamingService>) -> Self {
        Self { naming_service }
    }

    /// 注册服务实例
    pub async fn register_instance(
        &self,
        namespace: &str,
        service_name: &str,
        instance: ServiceInstance,
    ) -> Result<ApiResponse<()>> {
        let mut updated_instance = instance;
        updated_instance.namespace = namespace.to_string();
        updated_instance.group_name = "DEFAULT".to_string();
        updated_instance.service_name = service_name.to_string();
        
        self.naming_service.register_instance(&updated_instance)
            .await
            .map(|_| ApiResponse::success(()))
            .map_err(|e| NacosError::Internal(e.to_string()))
    }

    /// 注销服务实例
    pub async fn deregister_instance(
        &self,
        namespace: &str,
        service_name: &str,
        ip: &str,
        port: u16,
    ) -> Result<ApiResponse<()>> {
        let instance_id = format!("{}:{}", ip, port);
        self.naming_service.deregister_instance(namespace, "DEFAULT", service_name, &instance_id)
            .await
            .map(|_| ApiResponse::success(()))
            .map_err(|e| NacosError::Internal(e.to_string()))
    }

    /// 获取服务实例列表
    pub async fn get_instances(
        &self,
        namespace: &str,
        service_name: &str,
        healthy_only: bool,
    ) -> Result<ApiResponse<Vec<ServiceInstance>>> {
        let instances = if healthy_only {
            self.naming_service.get_healthy_instances(namespace, "DEFAULT", service_name)
                .await
                .map_err(|e| NacosError::Internal(e.to_string()))?
        } else {
            self.naming_service.get_all_instances(namespace, "DEFAULT", service_name)
                .await
                .map_err(|e| NacosError::Internal(e.to_string()))?
        };
        
        Ok(ApiResponse::success(instances))
    }

    /// 获取服务列表
    pub async fn get_services(
        &self,
        namespace: &str,
        page: u32,
        page_size: u32,
    ) -> Result<ApiResponse<Vec<String>>> {
        let services = self.naming_service.get_all_service_names(namespace, Some("DEFAULT"))
            .await
            .map_err(|e| NacosError::Internal(e.to_string()))?;
        
        Ok(ApiResponse::success(services))
    }

    /// 处理心跳
    pub async fn handle_heartbeat(
        &self,
        namespace: &str,
        service_name: &str,
        ip: &str,
        port: u16,
    ) -> Result<ApiResponse<()>> {
        let instance_id = format!("{}:{}", ip, port);
        self.naming_service.handle_heartbeat(namespace, "DEFAULT", service_name, &instance_id)
            .await
            .map(|_| ApiResponse::success(()))
            .map_err(|e| NacosError::Internal(e.to_string()))
    }
}

/// 配置服务API处理器
pub struct ConfigApiHandler {
    config_service: Arc<dyn ConfigService>,
}

impl ConfigApiHandler {
    pub fn new(config_service: Arc<dyn ConfigService>) -> Self {
        Self { config_service }
    }

    /// 发布配置
    pub async fn publish_config(
        &self,
        namespace: &str,
        group: &str,
        data_id: &str,
        content: &str,
    ) -> Result<ApiResponse<bool>> {
        let config = ConfigInfo {
            namespace: namespace.to_string(),
            group: group.to_string(),
            data_id: data_id.to_string(),
            content: content.to_string(),
            md5: None,
            last_modified: None,
        };

        let result = self.config_service.publish_config(namespace, group, data_id, content)
            .await
            .map_err(|e| NacosError::Internal(e.to_string()))?;
        
        Ok(ApiResponse::success(result))
    }

    /// 获取配置
    pub async fn get_config(
        &self,
        namespace: &str,
        group: &str,
        data_id: &str,
    ) -> Result<ApiResponse<ConfigInfo>> {
        let content = self.config_service.get_config(namespace, group, data_id)
            .await
            .map_err(|e| NacosError::Internal(e.to_string()))?;
        
        let config = ConfigInfo {
            namespace: namespace.to_string(),
            group: group.to_string(),
            data_id: data_id.to_string(),
            content: content.unwrap_or_default(),
            md5: None,
            last_modified: None,
        };
        
        Ok(ApiResponse::success(config))
    }

    /// 删除配置
    pub async fn delete_config(
        &self,
        namespace: &str,
        group: &str,
        data_id: &str,
    ) -> Result<ApiResponse<bool>> {
        let result = self.config_service.remove_config(namespace, group, data_id)
            .await
            .map_err(|e| NacosError::Internal(e.to_string()))?;
        
        Ok(ApiResponse::success(result))
    }

    /// 监听配置变更
    pub async fn listen_config(
        &self,
        namespace: &str,
        group: &str,
        data_id: &str,
        listener_id: &str,
    ) -> Result<ApiResponse<()>> {
        // 注：实际实现需要创建EventListener，这里简化处理
        // 在REST API中，监听通常通过长轮询或WebSocket实现
        Ok(ApiResponse::success(()))
    }
}

/// 集群API处理器
pub struct ClusterApiHandler {
    cluster_integration: Arc<crate::cluster_adapter::ClusterIntegrationManager>,
}

impl ClusterApiHandler {
    pub fn new(cluster_integration: Arc<crate::cluster_adapter::ClusterIntegrationManager>) -> Self {
        Self { cluster_integration }
    }

    /// 获取集群状态
    pub async fn get_cluster_status(&self) -> Result<ApiResponse<crate::cluster_adapter::ClusterStatus>> {
        let status = self.cluster_integration.get_cluster_status()
            .await
            .map_err(|e| NacosError::Internal(e.to_string()))?;
        
        Ok(ApiResponse::success(status))
    }

    /// 获取集群节点列表
    pub async fn get_cluster_nodes(&self) -> Result<ApiResponse<Vec<ClusterNode>>> {
        let nodes = self.cluster_integration.get_cluster_nodes()
            .await
            .map_err(|e| NacosError::Internal(e.to_string()))?;
        
        Ok(ApiResponse::success(nodes))
    }

    /// 添加集群节点
    pub async fn add_cluster_node(
        &self,
        node: ClusterNode,
    ) -> Result<ApiResponse<()>> {
        self.cluster_integration.add_cluster_node(node)
            .await
            .map(|_| ApiResponse::success(()))
            .map_err(|e| NacosError::Internal(e.to_string()))
    }

    /// 移除集群节点
    pub async fn remove_cluster_node(
        &self,
        node_id: &str,
    ) -> Result<ApiResponse<()>> {
        self.cluster_integration.remove_cluster_node(node_id)
            .await
            .map(|_| ApiResponse::success(()))
            .map_err(|e| NacosError::Internal(e.to_string()))
    }
}

/// REST API服务器
pub struct RestApiServer {
    config: ApiConfig,
    naming_handler: Arc<NamingApiHandler>,
    config_handler: Arc<ConfigApiHandler>,
    cluster_handler: Arc<ClusterApiHandler>,
}

impl RestApiServer {
    pub fn new(
        config: ApiConfig,
        naming_handler: Arc<NamingApiHandler>,
        config_handler: Arc<ConfigApiHandler>,
        cluster_handler: Arc<ClusterApiHandler>,
    ) -> Self {
        Self {
            config,
            naming_handler,
            config_handler,
            cluster_handler,
        }
    }

    pub async fn start(&self,
    ) -> Result<()> {
        info!("启动REST API服务器: 0.0.0.0:{}", self.config.rest_port);
        
        // 这里应该实现实际的服务器启动逻辑
        // 使用axum或warp等web框架
        
        Ok(())
    }

    pub async fn stop(&self,
    ) -> Result<()> {
        info!("停止REST API服务器");
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use nacos_core::MockNamingService;
    use nacos_core::MockConfigService;

    #[tokio::test]
    async fn test_naming_api_handler() {
        let naming_service = Arc::new(MockNamingService::new());
        let handler = NamingApiHandler::new(naming_service);

        // 测试注册实例
        let instance = ServiceInstance::default();
        let result = handler.register_instance("test-ns", "test-service", instance.clone()).await;
        assert!(result.is_ok());

        // 测试获取实例
        let instances = handler.get_instances("test-ns", "test-service", true).await;
        assert!(instances.is_ok());
    }

    #[tokio::test]
    async fn test_config_api_handler() {
        let config_service = Arc::new(MockConfigService::new());
        let handler = ConfigApiHandler::new(config_service);

        // 测试发布配置
        let result = handler.publish_config("test-ns", "test-group", "test-data", "test-content").await;
        assert!(result.is_ok());

        // 测试获取配置
        let config = handler.get_config("test-ns", "test-group", "test-data").await;
        assert!(config.is_ok());
    }
}
